package com.ruoyi.base.utils.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.util.Base64;

/**
 * 二维码工具类
 *
 * @author lcf
 */
public class QrCodeUtils {
    /**
     * 生成二维码
     */
    public static String getBase64QrCode(String content) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 350, 350);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败");
        }
    }
}
